<?php
/**
 * Mechanism
 * 
 * LICENSE
 * 
 * This file is private intellectual property of the author. 
 * All rights reserved. Copying and illegal using is punishable by law.
 * 
 * @copyright Copyright (c) 2011 BreatheInMyVoid ( BreatheInMyVoid@gmail.com )
 */

namespace Mechanism\Loader\Resource {
	class Gear extends Resource {
		protected $gears_dir = 'gears';
		protected $gears_ns = 'Gear';
		
		public function load( $name, $module = null ) {
			$name = ucfirst( $name );

			/* Load from global application path or module path */
			if ( null === $module ) {
				$path = $this->app_path 
						. $this->ds
						. $this->get_gears_dir( ) 
						. $this->ds
						. $name
						. '.php';
				
				$target = $this->get_app_namespace( )
						  . '\\' 
						  . $this->get_gears_ns( )
						  . '\\' 
						  . $name;
			} else {
				$module_namespace = ucfirst( $module );

				$path = $this->app_path 
						. $this->ds
						. $this->get_modules_dir( )
						. $this->ds
						. $module
						. $this->ds
						. $this->get_gears_dir( ) 
						. $this->ds
						. $name
						. '.php';
				
				$target = $this->get_app_namespace( )
						  . '\\' 
						  . $this->get_modules_namespace( )
						  . '\\'
						  . $module_namespace
						  . '\\'
						  . $this->get_gears_ns( )
						  . '\\' 
						  . $name;
			}

			if ( file_exists( $path ) && is_readable( $path ) ) {
				require_once $path;
			} else {
				throw new Exception\NotFound( 'Gear not found' );
			}


			if( class_exists( $target, false ) ) {
				return new $target;
			} else {
				throw new Exception\Invalid( 'Invalid Gear' );
			}
		}
		
		
		public function set_gears_dir( string $name ) {
			$this->gears_dir = $name;
		}
		
		public function set_gears_ns( string $ns ) {
			$this->gears_ns = $ns;
		}
		
		public function get_gears_dir( ) {
			return $this->gears_dir;
		}
		
		public function get_gears_ns( ) {
			return $this->gears_ns;
		}	
	}
}